using UniversalAdminSystem.Domian.Core;
using UniversalAdminSystem.Domian.Core.ValueObjects;
using UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;

namespace UniversalAdminSystem.Domian.PermissionManagement.Aggregate;

public class Role : AggregateRoot
{
    public RoleId RoleId { get; private set; } = null!;
    public RoleName Name { get; private set; } = null!;
    public RoleDescription? Description { get; private set; }
    public bool IsSystem { get; private set; } = false;
    public bool IsSupper { get; private set; } = false;
    public DateTime CreateTime { get; private set; } = DateTime.UtcNow;
    public DateTime UpdateTime { get; private set; } = DateTime.UtcNow;
    private readonly List<Permission> _permissions = [];
    public IReadOnlyCollection<Permission> Permissions => _permissions.AsReadOnly();
    public IReadOnlyCollection<Guid> PermissionIds => _permissions.Select(p => p.PermissionId).ToList().AsReadOnly();

    private Role() { }

    private Role(RoleName name, RoleDescription? description = null, bool isSystem = false, bool isSupper = false)
    {
        RoleId = RoleId.Create(Guid.NewGuid());
        Name = name;
        Description = description ?? RoleDescription.Create("暂无描述");
        IsSystem = isSystem;
        IsSupper = isSupper;
        CreateTime = DateTime.UtcNow;
        UpdateTime = DateTime.UtcNow;
        _permissions = new List<Permission>();
    }

    /// <summary>
    /// 角色工厂方法（支持描述、系统标记、超级管理员标记）
    /// </summary>
    public static Role Create(string name, string? description = null, bool isSystem = false, bool isSupper = false)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("角色名称不能为空");
        var role = new Role(RoleName.Create(name), string.IsNullOrWhiteSpace(description) ? null : RoleDescription.Create(description), isSystem, isSupper);

        return role;
    }

    /// <summary>
    /// 设置名称
    /// </summary>
    /// <param name="name"></param>
    /// <exception cref="ArgumentException"></exception>
    public void SetName(string name)
    {
        Name = RoleName.Create(name);
    }

    /// <summary>
    /// 设置描述
    /// </summary>
    /// <param name="description"></param>
    public void SetDescription(string? description)
    {
        Description = string.IsNullOrWhiteSpace(description) ? null : RoleDescription.Create(description);
    }

    /// <summary>
    /// 标记为超级管理员
    /// </summary>
    public void MarkAsSupper()
    {
        IsSupper = true;
    }

    /// <summary>
    /// 添加权限
    /// </summary>
    /// <param name="permission">权限实体</param>
    /// <exception cref="ArgumentException"></exception>
    public void AddPermission(Permission permission)
    {
        if (permission == null)
            throw new ArgumentException("权限不能为空", nameof(permission));

        if (!HasPermission(permission.PermissionId))
        {
            _permissions.Add(permission);
            UpdateTime = DateTime.UtcNow;
            
            // 添加权限分配事件
        }
    }

    /// <summary>
    /// 移除权限
    /// </summary>
    /// <param name="permission">权限实体</param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    /// <exception cref="InvalidOperationException"></exception>
    public void RemovePermission(Permission permission)
    {
        if (permission == null)
            throw new ArgumentException("权限不能为空", nameof(permission));

        var existingPermission = _permissions.FirstOrDefault(p => p.PermissionId == permission.PermissionId);
        if (existingPermission != null)
        {
            _permissions.Remove(existingPermission);
            UpdateTime = DateTime.UtcNow;
            
            // 添加权限移除事件
        }
    }

    /// <summary>
    /// 批量分配权限
    /// </summary>
    public void AddPermissions(IEnumerable<Permission> permissions)
    {
        foreach (var permission in permissions)
        {
            AddPermission(permission);
        }
    }

    /// <summary>
    /// 批量移除权限
    /// </summary>
    public void RemovePermissions(IEnumerable<Permission> permissions)
    {
        foreach (var permission in permissions)
        {
            RemovePermission(permission);
        }
    }

    /// <summary>
    /// 校验角色是否拥有某权限
    /// </summary>
    public bool HasPermission(Guid permissionId)
    {
        return _permissions.Any(p => p.PermissionId == permissionId);
    }

    /// <summary>
    /// 校验角色是否拥有全部指定权限
    /// </summary>
    public bool HasAllPermissions(IEnumerable<Guid> permissionIds)
    {
        return permissionIds.All(pid => _permissions.Any(p => p.PermissionId == pid));
    }

    /// <summary>
    /// 校验角色是否拥有任意指定权限
    /// </summary>
    public bool HasAnyPermission(IEnumerable<Guid> permissionIds)
    {
        return permissionIds.Any(pid => _permissions.Any(p => p.PermissionId == pid));
    }

    /// <summary>
    /// 检查角色是否有指定权限编码（通过权限ID匹配）
    /// </summary>
    /// <param name="permissionCode">权限编码</param>
    /// <param name="permissionId">对应的权限ID</param>
    /// <returns>是否有权限</returns>
    public bool HasPermission(string permissionCode, Guid permissionId)
    {
        // 这里需要根据权限编码找到对应的权限ID
        // 在实际使用中，可能需要通过权限服务来获取权限ID
        return HasPermission(permissionId);
    }

    /// <summary>
    /// 清空所有权限
    /// </summary>
    public void ClearPermissions()
    {
        _permissions.Clear();
        UpdateTime = DateTime.UtcNow;
    }

    /// <summary>
    /// 获取权限数量
    /// </summary>
    public int PermissionCount => _permissions.Count;
}